package com.yxhl.zoume.core.officialcar.fragment;


import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.custom.QuicklyClearEditText;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.car.activity.CarLocationMapActivity;
import com.yxhl.zoume.core.specialcar.model.CarLocationMapEntrance;
import com.yxhl.zoume.core.officialcar.activity.OfficialCarContainerActivity;
import com.yxhl.zoume.core.car.adapter.CarPOISearchAdapter;
import com.yxhl.zoume.core.car.model.SearchCityEvent;
import com.yxhl.zoume.core.specialcar.view.SearchPOIView;
import com.yxhl.zoume.core.func.map.presenter.location.POISearchPresenter;
import com.yxhl.zoume.di.component.car.DaggerSpecialCarComponent;
import com.yxhl.zoume.di.component.car.SpecialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.car.SpecialCarModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.SoftInputUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 项目名称：Ferrari
 * Created by menggod on 16/9/16 .
 * <p>
 * 选择地点里的查询POI的页面
 */
public class OfficialCarPOISearchFragment extends BaseFragment
        implements SearchPOIView, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener, TextWatcher {
    private static final String TAG = "OfficialCarPOISearchFragment";


    @BindView(R.id.linear_special_car_station_search_root)
    LinearLayout mLinearRoot;


    @BindView(R.id.et_special_search_keyword)
    QuicklyClearEditText mSearchInputEt;

    @BindView(R.id.tv_location_cancel)
    TextView mCancelTv;

    @BindView(R.id.recycler_location_search)
    RecyclerView mSearchRecycler;

    @BindView(R.id.iv_fragment_search_no_record)
    ImageView mNoResultIv;

    //arguments

    @Inject
    POISearchPresenter mPOISearchPresenter;
    @BindView(R.id.tv_city)
    TextView mTvCity;

    private List<String> mCityList;

    private CarLocationMapEntrance mEntrance;

    /**
     * 当前页面，从0开始计数
     */
    private int mCurrentPage = 0;

    /**
     * 定位城市名
     */
    private String mCurrentSelectedCity;


    private CarPOISearchAdapter mPOISearchAdapter;


    /**
     * 当前位置的POI信息
     */
    private PoiItem mCurrentLocationPoiItem;


    public OfficialCarPOISearchFragment() {
        // Required empty public constructor
    }

    public static OfficialCarPOISearchFragment newInstance(CarLocationMapEntrance entrance) {
        OfficialCarPOISearchFragment fragment = new OfficialCarPOISearchFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(UIConstants.Car.ARGUMENT_KEY_SPECIAL_CAR_POI_SEARCH_PARAM, entrance);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onRxBusEvent();
        parseArguments();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LOG.e(TAG, "onCreateView");
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mPOISearchPresenter.attachView(this);

        initSearchBar(mEntrance);
        initSearchEditText();
        initRecyclerView();
        setInitialStatus();
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onStop() {
        //SoftInputUtils.closeInputKeyboard(mActivity);
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        LOG.e(TAG, "onDestroyView");
        mSearchInputEt.removeTextChangedListener(this);

        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        LOG.e(TAG, "onDestroy");
    }

    private void onRxBusEvent() {
        getSubscription().add(toSubscription(SearchCityEvent.class,
                new Action1<SearchCityEvent>() {
                    @Override
                    public void call(SearchCityEvent searchCityEvent) {
                        if (searchCityEvent != null) {
                            String name = searchCityEvent.getCity();
                            if (!TextUtils.isEmpty(name)) {
                                mTvCity.setText(name);
                                mCurrentSelectedCity = name;
                                String content = mSearchInputEt.getText().toString().trim();
                                mPOISearchPresenter.doSearchPOIByKeyWord(mActivity, content, mCurrentPage, mCurrentSelectedCity);
                            }
                        }
                    }
                }

        ));
    }

    private void parseArguments() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mEntrance = (CarLocationMapEntrance) arguments.getSerializable(UIConstants.Car.ARGUMENT_KEY_SPECIAL_CAR_POI_SEARCH_PARAM);
        }
    }

    private void initSearchBar(CarLocationMapEntrance entrance) {
        Drawable drawableLeft;
        switch (entrance) {
            case SPECIAL_CAR_START:
            case OFFICIAL_CAR_SINGLE_WAY_GET_IN:
            case OFFICIAL_CAR_RENT_HOURLY_GET_IN:
                drawableLeft = getResources().getDrawable(R.drawable.ic_shangche);
                break;
            case SPECIAL_CAR_ARRIVAL:
            case OFFICIAL_CAR_SINGLE_WAY_GET_OFF:
                drawableLeft = getResources().getDrawable(R.drawable.ic_xiache);
                break;
            default:
                drawableLeft = getResources().getDrawable(R.drawable.ic_xiache);
        }
        mSearchInputEt.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
    }

    /**
     * UI状态重置
     */
    private void setInitialStatus() {
        //toolbar标题重置
        setupToolbarTitle();

        //搜索栏
        initSearchBar(mEntrance);

        FragmentManager supportFragmentManager = getActivity().getSupportFragmentManager();
        OfficialCarLocationMapFragment fragment = (OfficialCarLocationMapFragment) supportFragmentManager
                .findFragmentByTag(OfficialCarContainerActivity.FRAGMENT_CAR_LOCATION_MAP);
        String cityText = fragment.getCityText();
        mTvCity.setText(cityText);
        mCurrentSelectedCity = cityText;

        //搜索框数据重置
        mSearchInputEt.setText("");
        //列表数据重置
        mPOISearchAdapter.notifyEmpty();
        mNoResultIv.setVisibility(View.INVISIBLE);

        //获取当前位置POI
        mCurrentLocationPoiItem = getCurrentLocationPoiItem();

    }

    public void setEntrance(CarLocationMapEntrance entrance) {
        mEntrance = entrance;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LOG.e(TAG, "onHiddenChanged hidden=" + hidden);
        if (!hidden) {
            setInitialStatus();
        }
    }

    private void initSearchEditText() {
        mSearchInputEt.setOnEditorActionListener(this);
        mSearchInputEt.addTextChangedListener(this);
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mSearchRecycler.setLayoutManager(layoutManager);

        mPOISearchAdapter = new CarPOISearchAdapter(getContext(), new ArrayList<PoiItem>(), layoutManager);
        mSearchRecycler.setItemAnimator(new DefaultItemAnimator());
        mSearchRecycler.setAdapter(mPOISearchAdapter);

        //获取当前位置POI
        mCurrentLocationPoiItem = getCurrentLocationPoiItem();
    }

    private PoiItem getCurrentLocationPoiItem() {
        Fragment fragmentByTag;
        switch (mEntrance) {
            case OFFICIAL_CAR_SINGLE_WAY_GET_IN:
            case OFFICIAL_CAR_SINGLE_WAY_GET_OFF:
            case OFFICIAL_CAR_RENT_HOURLY_GET_IN:
                fragmentByTag = ((OfficialCarContainerActivity) mActivity)
                        .getSupportFragmentManager().findFragmentByTag(OfficialCarLocationMapFragment.class.getSimpleName());
                break;
            default:
                fragmentByTag = null;

        }

        if (fragmentByTag != null && fragmentByTag instanceof OfficialCarLocationMapFragment) {
            OfficialCarLocationMapFragment locationMapFragment = (OfficialCarLocationMapFragment) fragmentByTag;
            return locationMapFragment.getLocationPoiItem();
        }

        return null;
    }

    @OnClick(R.id.tv_location_cancel)
    public void onCancelClick() {
        SoftInputUtils.closeInputKeyboard(mActivity);
        switch (mEntrance) {
            case OFFICIAL_CAR_SINGLE_WAY_GET_IN:
            case OFFICIAL_CAR_SINGLE_WAY_GET_OFF:
            case OFFICIAL_CAR_RENT_HOURLY_GET_IN:
                //  ((OfficialCarContainerActivity) mActivity).displayOneFragment(OfficialCarContainerActivity.FRAGMENT_SINGLE_WAY, mEntrance);
                ((OfficialCarContainerActivity) mActivity).onBackPressed();
                break;
        }
    }

    /**
     * Spinner 选中监听
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mCurrentSelectedCity = mCityList.get(position);
        switch (mEntrance) {
            case OFFICIAL_CAR_SINGLE_WAY_GET_IN:
            case OFFICIAL_CAR_SINGLE_WAY_GET_OFF:
            case OFFICIAL_CAR_RENT_HOURLY_GET_IN:
                ((OfficialCarContainerActivity) mActivity).setUserSelectCity(mCurrentSelectedCity);
                break;
        }

        String content = mSearchInputEt.getText().toString().trim();
        if (!TextUtils.isEmpty(content)) {
            mPOISearchPresenter.doSearchPOIByKeyWord(mActivity, content, mCurrentPage, mCurrentSelectedCity);
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        LOG.e(TAG, "onEditorAction");
        String keyWord = mSearchInputEt.getText().toString();
        mPOISearchPresenter.doSearchPOIByKeyWord(mActivity, keyWord, mCurrentPage, mCurrentSelectedCity);
        return true;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s != null) {
            String searchKeyWord = s.toString();
            if (!TextUtils.isEmpty(searchKeyWord)) {
                mPOISearchPresenter.doSearchPOIByKeyWord(
                        mActivity,
                        searchKeyWord,
                        mCurrentPage,
                        mCurrentSelectedCity
                );
            } else {
                mPOISearchAdapter.notifyEmpty();
                mNoResultIv.setVisibility(View.VISIBLE);
            }

        }
    }

    @Override
    public void renderPOISearchResult(List<PoiItem> poiItems) {
        mPOISearchAdapter.notifyData(poiItems, mCurrentLocationPoiItem);
        if (poiItems.size() == 0) {
            mNoResultIv.setVisibility(View.VISIBLE);
        } else {
            mNoResultIv.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void renderPOISearchOnFailure() {
    }

    @Override
    protected void initializeInjector() {
        SpecialCarComponent specialCarComponent = DaggerSpecialCarComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .specialCarModule(new SpecialCarModule())
                .build();
        specialCarComponent.inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_official_car_location_search;
    }

    @Override
    protected void setupToolBar() {
        setupToolbarTitle();
    }

    private void setupToolbarTitle() {
        switch (mEntrance) {
            case OFFICIAL_CAR_SINGLE_WAY_GET_IN:
            case OFFICIAL_CAR_SINGLE_WAY_GET_OFF:
            case OFFICIAL_CAR_RENT_HOURLY_GET_IN:
                ((OfficialCarContainerActivity) mActivity).setToolbarTitle(getString(R.string.special_car_station_search));
                break;
            case EXPRESS_CAR_RENT_HOURLY_GET_IN:
            case EXPRESS_CAR_SINGLE_WAY_GET_IN:
            case EXPRESS_CAR_SINGLE_WAY_GET_OFF:
                ((CarLocationMapActivity) mActivity).setToolbarTitle(getString(R.string.special_car_station_search));
                break;
        }
    }
}
